import { computed, ref, watch } from 'vue'
import { getLyric } from '@/api/song'
import { useStore } from 'vuex'

function useLyric() {
  const lyric = ref(null)
  const { getters, commit } = useStore()
  const currentLine = ref(0)
  const scroll = ref(null)

  const currentSong = computed(() => {
    return getters['play/currentSong']
  })
  const lyricArray = computed(() => {
    const str = lyric.value
    if (!str) return []
    return lyric.value
      .split('\n')
      .filter(item => {
        return /^\[\d{2}:\d{2}\.\d{2}\].+$/.test(item)
      })
      .map(item => {
        const reg = /^\[(\d{2}):(\d{2})\.(\d{2})\](.+)$/
        return item
          .replace(reg, function(str, a, b, c, d) {
            const time = parseInt(a) * 60 + parseInt(b) + parseInt(c) / 1000
            return `${time},${d}`
          })
          .split(',')
      })
  })
  const currentLyric = computed(() => {
    const lyric = lyricArray.value[currentLine.value]
    return lyric && lyric[1]
  })

  watch(currentSong, newSong => {
    if (newSong.url && newSong.id) {
      if (newSong.lyric) {
        lyric.value = newSong.lyric
      } else {
        getLyricApi()
      }
    }
  })
  watch(currentLine, newLine => {
    const instance = scroll.value.scroll
    if (newLine < 6) {
      instance.scrollTo(0, 0, 200)
    } else {
      const distance = (newLine - 5) * 32
      const scrollDistance = Math.min(distance, -instance.maxScrollY)
      instance.scrollTo(0, -scrollDistance, 200)
    }
  })

  async function getLyricApi() {
    const res = await getLyric(currentSong.value)
    if (res) {
      commit('play/setSongLyric', { song: currentSong.value, lyric: res })
      if (currentSong.value.lyric !== res) return // 连续点击切换，异步请求可能造成 currentSong.lyric与当前接口的lyric不一致
      lyric.value = res
    }
  }

  function findCurrentLine(currentTime) {
    const lyricArr = lyricArray.value
    const length = lyricArr.length
    for (let i = 0; i < length; ++i) {
      if (i === length - 1) {
        if (currentTime >= parseFloat(lyricArr[i][0])) {
          currentLine.value = i
        }
      } else {
        const [curTime] = lyricArr[i]
        const [nextTime] = lyricArr[i + 1]
        if (
          currentTime >= parseFloat(curTime) &&
          currentTime < parseFloat(nextTime)
        ) {
          currentLine.value = i
        }
      }
    }
  }

  return {
    lyricArray,
    findCurrentLine,
    currentLine,
    scroll,
    currentLyric
  }
}

export default useLyric
